package de.windeln.marketing.campaign;

import java.util.Map;

import org.springframework.web.util.UriComponentsBuilder;

import com.google.common.base.Enums;
import com.google.common.base.Strings;
import com.google.common.collect.Maps;

import de.windeln.marketing.campaign.model.RequestClientObject;

public class CampaignValueGenerator {

	public void generate(RequestClientObject campaign) {
			ReasonCode requestedShop = Enums.getIfPresent(ReasonCode.class, campaign.getReasonCode()).or(ReasonCode.UNDEFINED);
		
			Map<String, String> uriVariables = Maps.newLinkedHashMap();
			if(!Strings.isNullOrEmpty(campaign.getAtInternetCode())){
				uriVariables.put("xtor", campaign.getAtInternetCode());
			}
			uriVariables.put("utm_source", campaign.getUtmSource());
			uriVariables.put("utm_medium", campaign.getUtmMedium());
			uriVariables.put("utm_campaign", campaign.getUtmCampaign());
			
			if(uriVariables.containsValue(null) || uriVariables.containsValue("")){
				return;
			}
			
			String analyticsLink;
			if(requestedShop == ReasonCode.UNDEFINED){
				String intelligentFallbackGeneration = campaign.getReasonCode().toLowerCase().replaceAll("_", ".");
				analyticsLink = generateAnalyticsLink(intelligentFallbackGeneration, uriVariables);
			}else{
				analyticsLink = generateAnalyticsLink(requestedShop.getDomain(), uriVariables);
			}
			campaign.setAnalyticsLink(analyticsLink);
	}

	private String generateAnalyticsLink(String domain, Map<String, String> uriVariables) {
//		String path = "http://www." + domain +"/?"+atInternetCodeParamValue+"utm_source=SOURCE&utm_medium=MEDIUM&utm_campagin=CAMPAIGN";
		UriComponentsBuilder builder = UriComponentsBuilder.fromPath("http:///www."+domain+"/");
		for (Map.Entry<String, String> entry : uriVariables.entrySet()){
			builder.queryParam(entry.getKey(), entry.getValue());
		}
		return builder.build().toUriString();
	}
}
